from PyQt5 import QtCore
import gl
from urllib import parse
from pydub import AudioSegment
import pyaudio
import wave
import sqlite3
import os
import threading
import httplib2


class Player(QtCore.QObject):
    input_str = ''
    output_file = ''
    finish_sgn=QtCore.pyqtSignal()

    def __init__(self):
        QtCore.QObject.__init__(self)

    def input(self,s):
        self.input_str = s
        self.output_file=gl.g_temp_dir+'/'+gl.get_temp_file_name('wav')

    def make_audio(self):
        conn = sqlite3.connect(gl.g_db_name)
        cur = conn.cursor()
        http = httplib2.Http(gl.g_http_catch_dir)
        cur.execute('SELECT bin FROM VOICE WHERE TEXT="'+self.input_str+'"')
        sql_data=cur.fetchall()
        if len(sql_data) != 0:
            fp = open(self.output_file, 'wb')
            fp.write(sql_data[0][0])
            fp.close()
            return True
        data = {
            'tex': self.input_str,
            'lan': 'zh',
            'tok': gl.g_token,
            'ctp': 1,
            'cuid': gl.get_mac_address(),
            'per':0
        }
        try:
            res, content = http.request('http://tsn.baidu.com/text2audio', 'POST', parse.urlencode(data))
            if res['content-type'] == ':application/json':
                return False
            else:
                fp = open(self.output_file+'.mp3', 'wb')
                fp.write(content)
                fp.close()
                sound = AudioSegment.from_mp3(self.output_file+'.mp3')
                sound.export(self.output_file, format="wav")
                os.remove(self.output_file+'.mp3')
                fp = open(self.output_file,'rb')
                content = fp.read()
                fp.close()
                conn.execute('INSERT INTO VOICE VALUES(?,?)',(self.input_str,sqlite3.Binary(content)))
                conn.commit()
                return True
        except Exception as Err:
            print(Err)
            return False

    def play(self):
        p = pyaudio.PyAudio()
        f = wave.open(self.output_file, "rb")
        stream = p.open(format=p.get_format_from_width(f.getsampwidth()),
                        channels=f.getnchannels(),
                        rate=f.getframerate(),
                        output=True)
        chunk = 1024
        data = f.readframes(chunk)
        while data != '':
            stream.write(data)
            data = f.readframes(chunk)
        stream.stop_stream()
        p.close(stream)
        p.terminate()
        f.close()
        os.remove(self.output_file)


def output(s):
    t = Player()
    t.input(s)
    t.make_audio()
    t.play()


def output_thread(s):
    t = threading.Thread(target=output,args=(s,))
    t.start()